"""
    数据库封装层
"""
import pymysql
class DBUtil:
    conn = None
    # 实列化类
    # 连接数据库
    @classmethod
    def __get_conn(cls):
        if cls.conn is None:

            cls.conn = pymysql.connect(host="localhost", port=3306, user="root", password="1234",
                                       database="sky_take_out", charset="utf8")
        return cls.conn
    # 关闭连接
    @classmethod
    def __close(cls):
        if cls.conn is not  None:
            cls.conn.close()
            # 置空
            cls.conn = None
    # 查询一条语句
    @classmethod
    def select_one(cls,sql):
        cursor = None
        result = None
        try:
            # 获取数据库连接
            cls.conn = cls.__get_conn()
            cursor = cls.conn.cursor()
            # 执行查询语句
            cursor.execute(sql)
            # 获取结果
            result =cursor.fetchone()

        except Exception as e:
            print(f"查询数据{sql}语句时出错{str(e)}")
        finally:
            # 关闭游标
            cursor.close()
            # 关闭数据库
            cls.__close()
            return result
    # 进行增删改sql语句操作
    @classmethod
    def uid_db(cls,sql):
        cursor = None

        try:
            # 获取数据库连接
            cls.conn = cls.__get_conn()
            cursor = cls.conn.cursor()
            # 执行查询语句
            cursor.execute(sql)
            # 提交数据
            cls.conn.commit()
        except Exception as e:
            print(f"增删改操作{sql}语句时出错{str(e)}")
            # 回滚操作
            cls.conn.rollback()
        finally:
            # 关闭游标
            cursor.close()
            # 关闭数据库
            cls.__close()



